import {Hono} from "hono";
import {getBlocksBySecuCode, getSecuBlocks, getSecuInfo, getTopNB1amt} from "@/backend/services/secu-service";


export const secuRouter = new Hono()
    .get('/info/:code', async (c) => {
        const {code} = c.req.param();
        const info = await getSecuInfo(code)
        return c.json({data: info})
    })
    .get('/uplimit', async (c) => {
        const topN = await getTopNB1amt()
        const topCodes = topN
            .filter(s => !s.secu_code.startsWith('68'))
            .map(t => t.secu_code);
        // console.log(topCodes)
        const blocks = await getBlocksBySecuCode(...topCodes);
        const keyBlocks = blocks.filter(b => ['tdx', 'cls'].includes(b.block_source))
        const keyBlockNames = keyBlocks.map(k => k.block_name);
        const keyCounter = keyBlockNames.reduce((obj: Record<string, number>, element) => {
            if (element !== null) {
                obj[element] = (obj[element] || 0) + 1
                // map.set(element, (map.get(element) || 0) + 1);
            }
            return obj
        }, {})

        const dataArr = Object.entries(keyCounter).sort((a, b) => b[1] - a[1]).slice(0, 3);
        // const data = Object.fromEntries(dataArr);
        const data = dataArr.reduce((prev, curr,) => {
            const currStr = `${curr.at(0)}（${curr.at(1)}）`
            if (prev === "") {
                return currStr
            }
            return prev + "" + currStr
        }, "")
        return c.json({data})
    });